<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <!-- 3. 动态class添加高亮 -->
      <!-- 4. 点击事件修改sorter -->
      <a  :class="{active: sorter  === 'weight_desc' }" href="javascript:;"   @click="sorter = 'weight_desc'">推荐</a >

      <a :class="{active: sorter  === null }" href="javascript:;" @click="sorter = null" >最新</a >

      <div class="logo"><img src="@/assets/logo.png" alt=""></div>

    </nav>

    <van-list @load="onLoadMore" v-model="isLoading"  :finished="isFinished"  finished-text="没有更多了">
      <article-item  v-for="item in list" :key="item.id" :item="item" @click="$router.push('/article/' + item.id)"/>
    </van-list>
  </div>

</template>

<script>
import ArticleItem from '@/components/ArticleItem.vue'
import { getArticlesAPI } from '@/api/article'
export default {
  name: 'article-page',
  components: {
    ArticleItem
  },
  data () {
    return {
      isLoading: false,
      list: [],
      current: 1,
      pageTotal: 999999,
      isFinished: false,
      sorter: 'weight_desc' // 1. weight_desc或者是null

    }
  },
  methods: {
    async loadData () {
      // 1. 加锁
      this.isLoading = true

      const res = await getArticlesAPI({
        current:
        this.current,
        sorter: this.sorter // 2.
      })
      this.list.push(...res.data.rows)
      this.isLoading = false
      this.current++
      this.pageTotal = res.data.pageTotal

      if (this.current > this.pageTotal) {
        this.isFinished = true
      }
    },
    onLoadMore () {
      this.loadData()
    }
  },
  watch: {
    sorter () {
      this.list = []
      this.current = 1
      this.isFinished = false
      // 2. 锁没打开的时候, 不再发请求
      if (!this.isLoading) {
        this.loadData()
      }
    }
  }

}
</script>

<style lang="less" scoped>
  .article-page {
    margin-bottom: 50px;
    margin-top: 44px;
    .my-nav {
      height: 44px;
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      z-index: 999;
      background: #fff;
      display: flex;
      align-items: center;
      > a {
        color: #999;
        font-size: 14px;
        line-height: 44px;
        margin-left: 20px;
        position: relative;
        transition: all 0.3s;
        &::after {
          content: '';
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          bottom: 0;
          width: 0;
          height: 2px;
          background: #222;
          transition: all 0.3s;
        }
        &.active {
          color: #222;
          &::after {
            width: 14px;
          }
        }
      }
      .logo {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        > img {
          width: 64px;
          height: 28px;
          display: block;
          margin-right: 10px;
        }
      }
    }
  }

</style>
